# -*- coding: utf-8 -*-
import os
import json
import xlrd
import sys 
import shutil
import importlib
importlib.reload(sys)

CEHUA_PATH = './generate'
CLIENT_PATH = '../ChessFireGame'

def readAudioPath():
    clientEffectPath = os.path.join(CLIENT_PATH,"assets/main-res/audio/effect")
    clientMusicPath = os.path.join(CLIENT_PATH,"assets/main-res/audio/music")

    fileContent = '\texport enum MusicName {\n'

    files = os.listdir(clientMusicPath)
    for fileName in files:
        if '.meta' in fileName:
            continue

        if '.DS_Store' in fileName:
            continue

        file_name_without_extension, file_extension = os.path.splitext(fileName)

        content = '\t\t"audio/music/{}" = "audio/music/{}",\n'.format(file_name_without_extension, file_name_without_extension)
        fileContent = fileContent + content
    
    fileContent = fileContent + "\t}\n"

    fileContent = fileContent + '\texport enum EffectName {\n'

    files = os.listdir(clientEffectPath)
    for fileName in files:
        if '.meta' in fileName:
            continue

        if '.DS_Store' in fileName:
            continue

        file_name_without_extension, file_extension = os.path.splitext(fileName)

        content = '\t\t"audio/effect/{}" = "audio/effect/{}",\n'.format(file_name_without_extension, file_name_without_extension)
        fileContent = fileContent + content
    
    fileContent = fileContent + "\t}\n"

    return fileContent

def writeConfigInterfaceFile(interfaceData):

    fileContent = 'import { ConfigOperation } from "./ConfigManager"\n'

    fileContent = fileContent + 'export module ConfigInterface {\n\n'

    fileContent = fileContent + "\texport interface IAppConfig {\n"

    for sheetName in sorted(interfaceData,reverse = False):
        interfaceName = "I" + sheetName[0].capitalize() + sheetName[1:] + "Config"

        newKey = sheetName[:1].lower() + sheetName[1:]

        configName = newKey + "Configs"



        fileContent = fileContent + "\t\treadonly " + configName + "?: ConfigOperation<" + interfaceName + ">\n"
    
    fileContent = fileContent + "\t}\n\n"

    for sheetName in sorted(interfaceData,reverse = False):
        sheet = interfaceData[sheetName]["sheet"]
        excelName = interfaceData[sheetName]["excelName"]

        # interfaces = sheet.row_values(0)

        interfaceName = "I" + sheetName[0].capitalize() + sheetName[1:] + "Config"

        fileContent = fileContent + "\t// From {} => {}\n".format(excelName,sheetName)
        fileContent = fileContent + "\texport interface {} {}".format(interfaceName,"{\n")

        
        fieldNames = sheet.row_values(0)
        typeNames = sheet.row_values(1)
        markContent = sheet.row_values(2)

        count = 0
        for filed in fieldNames:

            if filed == "":
                continue

            typeName = typeNames[count]

            if typeName != "string":
                typeName = "number"

            fileContent = fileContent + "\t\t/** " + markContent[count].replace("\n"," ") + " **/\n"
            fileContent = fileContent + "\t\treadonly " + filed + "?: " + typeName + "\n"
            count = count + 1
        
        fileContent = fileContent + "\t}\n\n"

        if sheetName == "value":

            valueKeys = sheet.col_values(0)[3:]

            markValues = sheet.col_values(2)[3:]


            enumName = "I" + sheetName[0].capitalize() + sheetName[1:] + "Enum"
            fileContent = fileContent + "\t// From {} => {}\n".format(excelName,sheetName)
            fileContent = fileContent + "\texport enum {} {}".format(enumName,"{\n")

            count = 0
            for valueKey in valueKeys:
                fileContent = fileContent + "\t\t/** " + markValues[count].replace("\n"," ") + " **/\n"
                fileContent = fileContent + "\t\t" + valueKey + " = " + '"{}",'.format(valueKey)   + "\n"
                count = count + 1


            fileContent = fileContent + "\t}\n\n"

    fileContent = fileContent + readAudioPath()

    fileContent = fileContent + "}"

    interfaceFile = os.path.join(CEHUA_PATH,'ConfigInterface.ts')
    f = open(interfaceFile,"w",encoding="utf-8")
    f.write(fileContent)
    f.close()
    pass

def readSheetContent(sheet,sheetName):
    fieldNames = sheet.row_values(0)
    typeNames = sheet.row_values(1)

    if fieldNames[0] != "id":
        print("error:first key must be 'id' for data's index")
        exit(0)
    
    rowCount = sheet.nrows

    configData = {}
    isError = False
    for row in range(3,rowCount):
        data = sheet.row_values(row)

        if data[0] == '':
            print("error: id is empty, sheetName:" + sheetName + " row:" + str(row))

        if isinstance(data[0],int) or isinstance(data[0], float):
            index = int(data[0])
        else:
            index = data[0]
        
        mapData = {}
        count = 0
        for filed in fieldNames:
            
            filedType = typeNames[count]
            filedData = data[count]


            if (filedType == "int" or filedType == "float") and filedData != "":
                if isinstance(filedData, float) or isinstance(filedData, int):

                    filedDataStr = str(filedData)

                    if filedDataStr.split(".")[1] == "0":
                        mapData[filed] = int(filedData)
                    else:
                        mapData[filed] = filedData  #float
                    
                elif isinstance(filedData,str):
                    filedData = filedData.strip()
                    if filedData.find('.') > 0:
                        filedData = float(filedData)
                    else:
                        filedData = int(filedData)

                    mapData[filed] = filedData
                else:

                    print("error:in line {} key ’{}‘ is {} {} but in excel is {} data is {}".format(row,filed,type(filedData),filedData,filedType,data))
                    isError = True  
                    
            if filedType == "string":
                ctype = sheet.cell(row, count).ctype

                if ctype == 2:
                    if filedData % 1 == 0:
                        filedData = int(filedData)


                mapData[filed] = ('{}'.format(filedData)).strip()

                if mapData[filed] == "":
                    del mapData[filed]

            
            count = count + 1
        configData[index] = mapData
    
    if isError:
        exit(0)

    return configData

def readExcelContent(excelPath,interfaceData,excelName,jsonContentData):
    data = xlrd.open_workbook(excelPath)
    sheets = data.sheet_names()
    
    print(excelPath)

    for sheetName in sheets :
        sheet = data.sheet_by_name(sheetName)
        print(sheetName)
        jsonContentData[sheetName] = readSheetContent(sheet,sheetName)
        interfaceData[sheetName] = {'sheet' : sheet,'excelName' : excelName}

    return jsonContentData

def copyConfigToProj():
    configPath = os.path.join(CEHUA_PATH,"configs")
    clientConfigPath = os.path.join(CLIENT_PATH,"assets/main-res/configs/")

    fileList = os.listdir(configPath)

    for fileName in fileList:
        filePath = os.path.join(configPath,fileName)
        shutil.copyfile(filePath,clientConfigPath + fileName)

    interfaceFile = os.path.join(CEHUA_PATH,'ConfigInterface.ts')
    clientInterfacePath = os.path.join(CLIENT_PATH,"assets/script/config/ConfigInterface.ts")
    shutil.copyfile(interfaceFile,clientInterfacePath)
    
    pass

if __name__=="__main__":
    configPath = os.path.join(CEHUA_PATH,"configs")
    excelsPath = os.path.join(CEHUA_PATH,"excels")
    fileList = os.listdir(configPath)
    
    for fileName in fileList:
        filePath = os.path.join(configPath,fileName)
        os.remove(filePath)

    interfaceData = {}
    jsonContentData = {}
    files = os.listdir(excelsPath)
    for fileName in files:

        if "~$" in fileName:
            continue
        
        print(fileName)
        if fileName != ".DS_Store":
            readExcelContent(os.path.join(excelsPath,fileName),interfaceData,fileName,jsonContentData)
        else:
            os.remove(os.path.join(excelsPath,fileName))

    configPath = os.path.join(CEHUA_PATH,"configs")
    jsonPath = os.path.join(configPath,"AppConfig.json")

    jsonData = json.dumps(jsonContentData, indent=4, separators=(',', ': '), ensure_ascii=False)

    f = open(jsonPath, "w",encoding="utf-8")
    f.write(jsonData)
    f.close()

    writeConfigInterfaceFile(interfaceData)
    copyConfigToProj()
